package com.aerozhonghuan.logisticsmall.framework.base;

import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.aerozhonghuan.foundation.log.LogUtil;
import com.aerozhonghuan.logisticsmall.BuildConfig;
import com.aerozhonghuan.logisticsmall.modules.user.beans.UserBean;
import com.aerozhonghuan.logisticsmall.modules.user.beans.UserInfo;
import com.aerozhonghuan.logisticsmall.modules.user.logic.UserInfoManager;
import com.aerozhonghuan.oknet2.RequestParaInterceptor;

import java.io.File;
import java.util.Map;
import java.util.UUID;

/**
 * 描述 请求参数 拦截器
 *
 * @author zhangyonghui
 * 创建日期 2019-05-17
 */
public class CustomRequestParaInterceptor implements RequestParaInterceptor {
    private static final String TAG = "RequestParaInterceptor";

    /**
     * @param injectPara 参数 有可能为空
     * @param headers
     */
    @Override
    public void onProcessCommonRequestPara(String url, @Nullable Map<String, String> injectPara, Map<String, String> headers) {
        LogUtil.i(TAG, "## 进入公共方法拦截器 onProcessCommonRequestPara");
        //为业务服务器地址,附加特殊参数
        if (injectPara != null) {
            UserInfo userInfo = UserInfoManager.getCurrentUserBaseInfo();
            if (isBusinessHost(url) && userInfo != null) {
                //对于已登录用户，每个带参数的http请求附加token参数
                injectPara.put("devId", userInfo.getDevId());
                injectPara.put("uuid", userInfo.getUuid());
                injectPara.put("token", userInfo.getToken());
                UserBean userBean = UserInfoManager.getCurrentUserDetailInfo();
                if (userBean != null && userBean.getCompany() != null) {
                    injectPara.put("sid", userBean.getCompany().getCode());
                }
            }
            injectPara.put("app", String.format("%s_%s_%s", "Android", BuildConfig.VERSION_NAME, BuildConfig.BUILD_TYPE));
            injectPara.put("timestamp", String.valueOf(System.currentTimeMillis()));
            injectPara.put("req-Id", UUID.randomUUID().toString());
        }
    }

    @Override
    public void onProcessUploadFileRequestPara(String url, @Nullable Map<String, String> paras, Map<String, File> fileParas, Map<String, String> headers) {
        LogUtil.i(TAG, "## 进入公共方法拦截器 onProcessUploadFileRequestPara");
    }

    /**
     * 判断url是否是访问 业务服务器
     *
     * @param url
     * @return
     */
    private boolean isBusinessHost(String url) {
        boolean isAuthUrl = url.contains(URLs.SERVER_PUSH_DEVICE) || url.contains(URLs.SERVER_UPDATE_DEVICE) || url.contains(URLs.SERVER_CHECK_TOKEN) || url.contains(URLs.SERVER_LOGOUT);
        return !TextUtils.isEmpty(url) && !isAuthUrl;
    }
}
